package com.weihua.config;

import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.time.LocalDateTime;

@Slf4j
@Component
public class ColumnMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject meta) {
        if(log.isDebugEnabled()) {
            log.debug("auto fill insert field");
        }
        Field[] fields=meta.getOriginalObject().getClass().getDeclaredFields();
        for(Field field: fields){
            Annotation[] annotations = field.getAnnotations();
            if(annotations!=null && annotations.length>0){
                for (Annotation ann:annotations) {
                    if(ann instanceof TableField){
                        if(((TableField) ann).fill().equals( FieldFill.INSERT)
                                ||((TableField) ann).fill().equals( FieldFill.INSERT_UPDATE)){
                            if(((Class) field.getGenericType()).getName().equals(LocalDateTime.class.getName())){
                                this.setFieldValByName(field.getName(), LocalDateTime.now(), meta);
                            }
                        }
                    }
                }
            }
        }

    }

    @Override
    public void updateFill(MetaObject meta) {
        if(log.isDebugEnabled()) {
            log.debug("auto fill update field");
        }
        Field[] fields=meta.getOriginalObject().getClass().getDeclaredFields();
        for(Field field: fields){
            Annotation[] annotations = field.getAnnotations();
            if(annotations!=null && annotations.length>0){
                for (Annotation ann:annotations) {
                    if(ann instanceof TableField){
                        if(((TableField) ann).fill().equals( FieldFill.UPDATE)
                                ||((TableField) ann).fill().equals( FieldFill.INSERT_UPDATE)){
                            if(((Class) field.getGenericType()).getName().equals(LocalDateTime.class.getName())){
                                this.setFieldValByName(field.getName(), LocalDateTime.now(), meta);
                            }
                        }
                    }
                }
            }
        }

    }
}
